
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试 websocket 世界最简单案例</title>
</head>
<body>
    <script type="text/javascript">
    var ws;//一个ws对象就是一个通信管道
    //target就是要连接服务端的地址 刚好和服务端的websocket进行匹配和服务器端中表重要部分对应
    var target = "ws://0.0.0.0:8001/test1";
  	function subOpen(){
  	    //类似于ajax中兼容浏览器的处理
  		if("WebSocket"in window){
  			ws = new WebSocket(target);
  		}
  		else if("MozWebSocket" in window){
  			ws = new MozWebSocket(target);
  		}
  		else{
  			alert("WebSocket is not supported by this browser.");
  			return;
  		}

  		//获取客户端的消息，传递到服务端
  		ws.onmessage=function(event){
  			var dv = document.getElementById("dv");
  			dv.innerHTML+=event.data;
  		};

  	    switch (ws.readyState) {
          case WebSocket.CONNECTING:
            t = 1
            break;
          case WebSocket.OPEN:
            t = 2
            break;
          case WebSocket.CLOSING:
            t = 3
            break;
          case WebSocket.CLOSED:
            t = 4
           break;
          default:
            // this never happens
            break;
        }

  	document.getElementById("t").innerHTML=t + "<br />";
  	}
  	//发送消息的事件
  	function subSend(){
  		<!--var msg = document.getElementById("msg").value;-->
  		<!--ws.send(msg);-->
  		<!--document.getElementById("msg").value = "";-->

  		ws.send('your send!')
  		ws.readyState = WebSocket.OPEN



  		<!--/!!!-->
  		<!--这里两个方案：-->
  		<!--1.查询前端状态马，直接改写-->
  		<!--2.联合发送ping/pong-->
  		<!--!!!不能再在这里浪费时间了-->
  		<!--!!!要开始写后端逻辑了-->
  		<!--!!!把这个给前端去想或者问-->
  		2019-3-13 23:53


  		switch (ws.readyState) {
          case WebSocket.CONNECTING:
            t = 0
            break;
          case WebSocket.OPEN:
            t = 1
            break;
          case WebSocket.CLOSING:
            t = 2
            break;
          case WebSocket.CLOSED:
            t = 3
           break;
          default:
            // this never happens
            break;
        }

  	document.getElementById("t").innerHTML=t + "<br />";
  	}




  </script>
  <body>
      <br>
      <button onclick="subOpen();">open</button>
  	  <input id="msg"/>
      <button onclick="subSend();">send</button>

      <p id="t" style="color: blueviolet;"></p>
      <span id="dv"></span>
  </body>
</body>
</html>